package com.maigang.service.impl.customer;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import com.maigang.dao.common.CartMapper;
import com.maigang.dao.common.ProductMapper;
import com.maigang.pojo.common.Cart;
import com.maigang.pojo.common.Product;
import com.maigang.pojo.vo.CartProductVo;
import com.maigang.pojo.vo.CartVo;
import com.maigang.service.customer.ICartService;
import com.maigang.utils.common.BigDecimalUtil;
import com.maigang.utils.common.Const;
import com.maigang.utils.common.ResponseCode;
import com.maigang.utils.common.ServerResponse;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

/**
 * @ClassName:
 * @Description:
 * @author: yubao.jin
 * @date: 2018/4/9
 * @version:V1.0
 */
@Service("iCartService")
public class CartServiceImpl implements ICartService {
	@Autowired
    private CartMapper cartMapper;

    @Autowired
    private ProductMapper productMapper;

	public ServerResponse<CartVo> add(Integer userId, Integer productId, Integer count, Integer isPresale,
			Integer pageNum, Integer pageSize) {
        // 检验参数的合法
		if(productId == null || count == null || checkProduct(productId) == false) {
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }

        Cart cart = cartMapper.selectCartByUserIdProductId(userId, productId, isPresale);
        if(cart == null) {
            // 这个产品不在这个购物车里，需要新增一个这个产品的记录
            Cart cartItem = new Cart();
            cartItem.setQuantity(count);
            cartItem.setChecked(Const.Cart.CHECKED);
            cartItem.setProductId(productId);
            cartItem.setUserId(userId);
            cartItem.setIsPresale(isPresale);
            cartMapper.insertSelective(cartItem);
        } else {
            // 这个产品已经在购物车里了.
            // 如果产品已存在，数量相加
            count = cart.getQuantity() + count;
            cart.setQuantity(count);
            cartMapper.updateByPrimaryKeySelective(cart);
        }
        return this.list(userId, pageNum, pageSize);
	}

	public ServerResponse<CartVo> update(Integer userId, Integer cartId, Integer count,
			Integer pageNum, Integer pageSize) {
		if(cartId == null || count == null) {
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }

        Cart cart = cartMapper.selectCartByUserIdCartId(userId, cartId);
        if(cart != null) {
            cart.setQuantity(count);
        }
        cartMapper.updateByPrimaryKeySelective(cart);
        return this.list(userId, pageNum, pageSize);
	}

	public ServerResponse<CartVo> deleteProduct(Integer userId, String projectIds, Integer pageNum, Integer pageSize) {
        // 去除空格避免影响in(sql)
        if(projectIds.length() > 0) {
            projectIds = projectIds.substring(0, projectIds.length() - 1);
        }
		List<String> productList = Splitter.on(",").splitToList(projectIds);
        if (CollectionUtils.isEmpty(productList)) {
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }

        cartMapper.deleteByUserIdProductIds(userId, productList);
        return this.list(userId, pageNum, pageSize);
	}

	public ServerResponse<CartVo> list(Integer userId, Integer pageNum, Integer pageSize) {
		 CartVo cartVo = this.getCartVoLimit(userId, pageNum, pageSize);
	        return ServerResponse.createBySuccess(cartVo);
	}

	public ServerResponse<CartVo> selectOrUnselect(Integer userId, Integer productId, Integer checked, Integer pageNum,
			Integer pageSize, String projectIds) {
        // 去除空格避免影响in(sql)
        if(projectIds.length() > 0) {
            projectIds = projectIds.substring(0, projectIds.length() - 1);
        }
        List<String> productList = Splitter.on(",").splitToList(projectIds);
        if (CollectionUtils.isEmpty(productList)) {
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }

		cartMapper.checkedUncheckedProduct(userId, productId, checked, productList);
        return this.list(userId, pageNum, pageSize);
	}

	public ServerResponse<Integer> getCartProductCount(Integer userId) {
		if(userId == null) {
            return ServerResponse.createBySuccess(0);
        }
        return  ServerResponse.createBySuccess(cartMapper.selectCartProductCount(userId));
	}
    
	private CartVo getCartVoLimit(Integer userId, Integer pageNum, Integer pageSize) {
        CartVo cartVo = new CartVo();
        PageHelper.startPage(pageNum, pageSize);
        List<Cart> cartList = cartMapper.selectCartByUserId(userId);
        PageInfo<Cart> pageInfo = new PageInfo(cartList);
        pageInfo.setList(cartList);
        List<CartProductVo> cartProductVoList = Lists.newArrayList();
        BigDecimal cartTotalPrice = new BigDecimal("0");

        if(CollectionUtils.isNotEmpty(cartList)) {
            for(Cart cartItem : cartList) {
                CartProductVo cartProductVo = new CartProductVo();
                cartProductVo.setId(cartItem.getId());
                cartProductVo.setUserId(userId);
                cartProductVo.setProductId(cartItem.getProductId());

                Product product = productMapper.selectByPrimaryKey(cartItem.getProductId());
                if(product != null) {
                    cartProductVo.setProductMainImage(product.getMainImage());
                    cartProductVo.setProductName(product.getName());
                    cartProductVo.setProductPrice(product.getPrice());
                    cartProductVo.setProductStatus(product.getStatus());
                    cartProductVo.setProductStock(product.getStock());
                    cartProductVo.setProductStock(product.getReserveStock());

                    // 判断库存
                    int buyLimitCount = 0;
                    if(cartItem.getIsPresale() == 0) {
                        if(product.getStock() >= cartItem.getQuantity()) {
                            // 库存充足时
                            buyLimitCount = cartItem.getQuantity();
                            cartProductVo.setLimitQuantity(Const.Cart.LIMIT_NUM_SUCCESS);
                        } else {
                            buyLimitCount = product.getStock();
                            cartProductVo.setLimitQuantity(Const.Cart.LIMIT_NUM_FAIL);
                            // 购物车中更新有效库存
                            Cart cartForQuantity = new Cart();
                            cartForQuantity.setId(cartItem.getId());
                            cartForQuantity.setQuantity(buyLimitCount);
                            cartMapper.updateByPrimaryKeySelective(cartForQuantity);
                        }
                    } else {
                        if(product.getReserveStock() >= cartItem.getQuantity()) {
                            // 库存充足时
                            buyLimitCount = cartItem.getQuantity();
                            cartProductVo.setLimitQuantity(Const.Cart.LIMIT_NUM_SUCCESS);
                        } else {
                            buyLimitCount = product.getReserveStock();
                            cartProductVo.setLimitQuantity(Const.Cart.LIMIT_NUM_FAIL);
                            // 购物车中更新有效库存
                            Cart cartForQuantity = new Cart();
                            cartForQuantity.setId(cartItem.getId());
                            cartForQuantity.setQuantity(buyLimitCount);
                            cartMapper.updateByPrimaryKeySelective(cartForQuantity);
                        }
                    }
                    cartProductVo.setQuantity(buyLimitCount);
                    // 计算总价
                    cartProductVo.setProductTotalPrice(BigDecimalUtil.mul(product.getPrice().doubleValue(), cartProductVo.getQuantity()));
                    cartProductVo.setProductChecked(cartItem.getChecked());
                }
                if(cartItem.getChecked() == Const.Cart.CHECKED) {
                    // 如果已经勾选，增加到整个购物车总价中
                    cartTotalPrice = BigDecimalUtil.add(cartTotalPrice.doubleValue(), cartProductVo.getProductTotalPrice().doubleValue());
                }
                cartProductVoList.add(cartProductVo);
            }
        }
        cartVo.setCartTotalPrice(cartTotalPrice);
        cartVo.setCartProducVoList(cartProductVoList);
        cartVo.setAllChecked(this.getAllCheckedStatus(userId));
        cartVo.setImageHost("////");
        cartVo.setPageInfo(pageInfo);
        return cartVo;
    }

    private boolean getAllCheckedStatus(Integer userId) {
        if(userId == null) {
            return false;
        }
        return cartMapper.selectCartProductCheckedStatusByUserId(userId) == 0;
    }

    // 检验此产品是否存在
    private Boolean checkProduct(Integer productId){
        Product product = productMapper.selectByPrimaryKey(productId);
        return product == null;
    }
}
